<?php
// 应用公共文件

use app\common\service\AuthService;
use think\facade\Cache;

if (!function_exists('__url')) {

    /**
     * 构建URL地址
     *
     * @param string $url
     * @param array  $vars
     * @param bool   $suffix
     * @param bool   $domain
     *
     * @return string
     */
    function __url(string $url = '', array $vars = [], $suffix = true, $domain = false)
    {
        return url($url, $vars, $suffix, $domain)->build();
    }
}

if (!function_exists('password')) {

    /**
     * 密码加密算法
     *
     * @param $value 需要加密的值
     * @param $type  加密类型，默认为md5 （md5, hash）
     *
     * @return mixed
     */
    function password($value)
    {
        $value = sha1('blog_') . md5($value) . md5('_encrypt') . sha1($value);
        return sha1($value);
    }

}

if (!function_exists('xdebug')) {

    /**
     * debug调试
     *
     * @param string|array $data   打印信息
     * @param string       $type   类型
     * @param string       $suffix 文件后缀名
     * @param bool         $force
     * @param null         $file
     *
     * @deprecated 不建议使用，建议直接使用框架自带的log组件
     */
    function xdebug($data, $type = 'xdebug', $suffix = null, $force = false, $file = null)
    {
        !is_dir(runtime_path() . 'xdebug/') && mkdir(runtime_path() . 'xdebug/');
        if (is_null($file)) {
            $file = is_null($suffix) ? runtime_path() . 'xdebug/' . date('Ymd') . '.txt' : runtime_path() . 'xdebug/' . date('Ymd') . "_{$suffix}" . '.txt';
        }
        file_put_contents($file, "[" . date('Y-m-d H:i:s') . "] " . "========================= {$type} ===========================" . PHP_EOL, FILE_APPEND);
        $str = (is_string($data) ? $data : (is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
        $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
    }
}

if (!function_exists('sysconfig')) {

    /**
     * 获取系统配置信息
     *
     * @param        $group
     * @param null   $name
     * @param string $default
     * @param string $field
     *
     * @return string
     */
    function sysconfig($group, $name = null, $default = '', $field = 'value')
    {
        $where = ['group' => $group];
        $value = empty($name) ? Cache::get("sysconfig_{$group}_{$field}") : Cache::get("sysconfig_{$group}_{$name}_{$field}");
        if (empty($value)) {
            if (!empty($name)) {
                $where['name'] = $name;
                $_value = \app\admin\model\SystemConfig::where($where)->value($field);
                $value = $value==$_value?$value:$_value;
                Cache::tag('sysconfig')->set("sysconfig_{$group}_{$name}_{$field}", $value, 180);
            } else {
                $value = \app\admin\model\SystemConfig::where($where)->column($field, 'name');
                Cache::tag('sysconfig')->set("sysconfig_{$group}_{$field}", $value, 180);
            }
        }
        return $value ?: $default;
    }
}

if (!function_exists('array_format_key')) {

    /**
     * 二位数组重新组合数据
     *
     * @param $array
     * @param $key
     *
     * @return array
     */
    function array_format_key($array, $key)
    {
        $newArray = [];
        foreach ($array as $vo) {
            $newArray[$vo[$key]] = $vo;
        }
        return $newArray;
    }

}

if (!function_exists('auth')) {

    /**
     * auth权限验证
     *
     * @param $node
     *
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function auth($node = null)
    {
        $authService = new AuthService(session('admin.id'));
        $check = $authService->checkNode($node);
        return $check;
    }
}
if (!function_exists('encrypt')) {
    function encrypt($string, $operation = 'ENCODE', $key = '', $expiry = 0)
    {
        if ($operation == 'DECODE') {
            $string = rtrim($string, '__jswei');
            $string = str_replace('[a]', '+', $string);
            $string = str_replace('[b]', '&', $string);
            $string = str_replace('[c]', '/', $string);
        }
        $ckey_length = 4;
        $key = md5($key ? $key : 'shaitaiyangdepaopao');
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()),
            -$ckey_length)) : '';
        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);
        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d',
                $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);
        $result = '';
        $box = range(0, 255);
        $rndkey = array();
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }
        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }
        if ($operation == 'DECODE') {
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10,
                    16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {

                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            $ustr = $keyc . str_replace('=', '', base64_encode($result));
            $ustr = str_replace('+', '[a]', $ustr);
            $ustr = str_replace('&', '[b]', $ustr);
            $ustr = str_replace('/', '[c]', $ustr);
            return $ustr . '__jswei';
        }
    }
}
